package com.geek.water.interceptor;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;

import com.geek.water.constant.CodeConstant;
import com.geek.water.constant.MessageConstant;
import com.geek.water.result.Result;
import com.geek.water.utils.JwtHelper;
import com.geek.water.utils.WebUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 移动端的登陆拦截器
 * @author chemin
 */
public class AuthInterceptor implements HandlerInterceptor {

    /**
     * 在执行handler之前：登陆拦截、权限拦截等
     * @param request 请求
     * @param response 响应
     * @param handler 处理的handler
     * @return true代表放行  false代表不放行
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.从请求头中获取token数据
        String token = request.getHeader("token");
        if(StrUtil.isEmpty(token)){
            WebUtils.renderString(response , JSONUtil.toJsonStr(new Result(CodeConstant.FAIL, MessageConstant.TOKEN_EMPTY)));
            return false;
        }

        //2.验证其是否过期
        if(JwtHelper.isExpiration(token)){
            WebUtils.renderString(response , JSONUtil.toJsonStr(new Result(CodeConstant.FAIL, MessageConstant.ACCESS_TOKEN_VERIFY_FAIL)));
            return false;
        }

        //3.解析token中的数据
        Long memberId = JwtHelper.getUserId(token);
        if(memberId==null){
            WebUtils.renderString(response , JSONUtil.toJsonStr(new Result(CodeConstant.FAIL, MessageConstant.TOKEN_ILLEGAL)));
            return false;
        }

        return true;
    }
}
